package ui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.Timer;
import javax.swing.JFrame;

import model.Game;
import model.Score;

@SuppressWarnings("serial")
public class Pong extends JFrame {
	
	private static final int INTERVAL = 20;
	private Game game;
	private GamePanel gp;
	private Score s;
	private Timer t;
	
	public Pong() {
		super("Pong");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setUndecorated(true);
		game = new Game();
		s = new Score(game);
		gp = new GamePanel(game, s);
		add(gp);
		addKeyListener(new KeyHandler());
		pack();
		centreOnScreen();
		setVisible(true);
		addTimer();
		t.start();
	}
	
	private void addTimer() {
		t = new Timer(INTERVAL, new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent ae) {
				game.update();
				gp.repaint();
			}
		});
	}
	
	private void centreOnScreen() {
		Dimension scrn = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation((scrn.width - getWidth()) / 2, (scrn.height - getHeight()) / 2);
	}
	
	private class KeyHandler extends KeyAdapter {
		@Override
		public void keyPressed(KeyEvent e) {
			game.keyPressed(e);
		}
		@Override
		public void keyReleased(KeyEvent e) {
			game.keyReleased(e);
		}
	}
	
	public static void main(String[] args) {
		new Pong();
	}
}
